from PySide2.QtGui import QPixmap

from forms.uipy.UI_EleHouseVisitRecords import Ui_EleHouseVisitRecords
from PySide2.QtWidgets import QWidget, QLayout, QPushButton
import pandas as pd

from tools.Area_Objects import areaObjs
from tools.Area_tools import Area_Tools
from tools.Charts_Tools import Charts_Tools
from tools.File_Select_Tools import File_Select_Tools
from tools.Time_Tools import Time_Tools
from tools.Conver_Tools import Conver_Tools
from tools.MatplotlibChartsTools.BarChartTools import BarChartTools


class EleHouseVisitRecordsImpl(QWidget, Ui_EleHouseVisitRecords):
    """
    电子访户记录业务类
    """

    def __init__(self):

        # # 选择访户记录文件
        # self.file_path =  File_Select_Tools.select_one_file(title="访户记录文件")[0]
        super().__init__()
        self.setupUi(self)

        # 初始化下拉选择框数据
        for area in areaObjs[1:]:
            self.area_datas.addItem(area['name'], userData=area['No'])
        # 初始化数据
        self.init_data()

        # 绑定下拉选择框事件
        self.area_datas.activated.connect(self.area_selected_changed)



        # 插入图表
        # self.left_bar.actions()
        self.left_bar = BarChartTools()
        self.right_bar = BarChartTools()
        # self.left_bar_show = QWidget()
        # self.right_bar_show = QWidget()

        # self.bar_clicked(0)
        self.showbars.addWidget(self.left_bar.canvas)

        self.showbars.addWidget(self.right_bar.canvas)

        self.area_selected_changed()

    def area_selected_changed(self):
        self.area_id = self.area_datas.currentData()
        self.area_name = Area_Tools.get_area_name(self.area_id)

        selected = []
        if self.errorData.get(str(self.area_id)) is None:
            selected = []
        else:
            selected = self.errorData.get(str(self.area_id))

        area_bar_data = self.get_area_data(str(self.area_id))
        self.left_bar.update_data(area_bar_data.get("point"),area_bar_data.get("data"),area_bar_data.get("point"),self.bar_clicked)
        self.left_bar.set_title(str(self.mouth) + "月" + self.area_name + "访户记录汇总情况")
        # 设置访户不足
        self.left_bar.default_item([i-1 for i in selected])

        #
        # if type(_left) is not QWidget:
        #     self.showbars.replaceWidget(_left.canvas, self.left_bar_show.canvas)
        # else:
        #     self.showbars.replaceWidget(_left, self.left_bar_show.canvas)
        # 默认第一点显示
        # self.bar_clicked(0)

    def init_data(self):
        # 初始化数据
        # 加载住户样本数据
        house_df = pd.read_csv(r'./res/访户记录/住户样本.csv', encoding='GBK')
        # file_path = "./res/访户记录/辅导员监控.5105.20247.20240801.134654.csv"
        # 加载访户数据
        house_records_df = pd.read_csv(self.file_path, encoding='GBK')
        # 获取导出年份月份
        self.year_mouth = Time_Tools.get_file_year_mouth(self.file_path, "5105.")
        self.mouth = Time_Tools.get_file_mouth(self.file_path, "5105.")

        # 组装住户样本数据
        ## 获取住户所在点位
        house_df['Point'] = house_df['户编码'].apply(lambda scode: str(scode)[0:str(scode).find(".")]).astype(int)
        house_df['县码'] = house_df['住户ID'].str[0:6]
        # 排除新开户的情况
        house_df = house_df[house_df["开户时间"] < self.year_mouth]
        records_df = pd.DataFrame(house_records_df.groupby('被访户编码').size().reset_index(name="count"))
        # 将访户数据挂载
        self.records_df = pd.merge(house_df, records_df, left_on='住户ID', right_on="被访户编码", how='left')
        # 将空值填为0
        self.records_df.fillna({"count": 0}, inplace=True)

        # 过滤不符合条件的区县和点位 访户次数 < 2 次  户数 < 10 户
        showAllData = self.records_df[self.records_df['count'] < 2][['县码', 'Point', '户编码', 'count']]

        self.errorData = Conver_Tools.list_to_dict(list(pd.DataFrame(showAllData.groupby(['县码', 'Point']))[0]))

    def get_area_data(self, area_code) -> dict:
        """
        通过区域ID，获取访户数据
        :param area_code: 区域ID
        :return: 返回包含访户数据字典，point,data key  value 一维数组
        """
        # 筛选对应县区
        dataDf = self.records_df[self.records_df['县码'] == str(area_code)].copy()
        # 汇总访户次数
        dataDf = pd.DataFrame(dataDf.groupby('Point')['count'].sum().reset_index())
        return {
            "point": list(dataDf['Point']),
            "data": list(dataDf['count'])
        }

    def get_area_and_points(self, area_code, point) -> dict:
        """
        通过区域ID和点位point获取访户数据
        :param area_code: 区域ID
        :param point: 点位
        :return: 返回包含访户数据字典，point,data key  value 一维数组
        """

        # 筛选对应县区和点位几访户次数
        dataDf = self.records_df[(self.records_df['县码'] == str(area_code)) & (self.records_df['Point'] == point)]

        return {
            "houseID": list(dataDf['户编码']),
            "data": list(dataDf['count'])
        }

    def bar_clicked(self,event):
        i = self.left_bar.clicked_item_category(event)
        area_bar_data = self.get_area_and_points(self.area_id, i)
        self.right_bar.update_data(area_bar_data.get("houseID"), area_bar_data.get("data"))
        self.right_bar.set_title(str(self.mouth) + "月" + self.area_name + str(i) + "点访户记录数量")

